(ns ifeast.recipes.parsers.extractor
  "Functions for extracting recipe data from arbitrary html pages.
  Uses Microdata, Microformats, or RDFa."
  (:use    [net.cgrand.enlive-html :only (select html-resource text attr? attr=)])
  (:require [clojure.contrib.str-utils2 :as s])
  (:import java.net.URL))


(def microformat-selectors
  (set (concat
    ; Standard hrecipe tags
    (map #(conj [:.hrecipe] %)
         [:.fn 
          :.ingredient
          :.yield
          :.instructions
          :.duration
          :.photo
          :.summary
          :.author
          :.published
          :.nutrition
          :.tag])
    ; Special cases for allrecipes.com
    (map #(conj [:.hRecipe] %)
         [:.fn
          :.ingredient
          :.yield
          :.directions
          :.photo]))))

(def microdata-selectors
  #{[(attr= :itemtype "http://schema.org/Recipe") (attr? :itemprop)]})

(defn fetch-url [url]
  (html-resource (URL. url)))

(defn extract-microformat-data [resource]
  "Returns... TODO"
  (select resource #{[:.hrecipe] [:.hRecipe]}))

(defn extract-microdata-data [resource]
  "Returns... TODO"
  (select resource microdata-selectors))

(defn print-recipe [tags]
  (for [tag tags]
    (let [{content :content {class :class} :attrs} tag]
      (cond (s/contains? class "fn") (println "name: " (apply str content))
            (s/contains? class "ingredient") (println "ingredient: " (apply str content))))))
            
;(print-recipe (extract-microformat-data (fetch-url "http://allrecipes.com/recipe/ole-party-salsa/detail.aspx")))
;(print-recipe (extract-microformat-data (fetch-url "http://www.epicurious.com/recipes/food/views/Shortbread-Cookies-367140")))
;(extract-microdata-data (fetch-url "http://sweetfry.com/recipe/284/Apple-Crisp"))
(extract-microdata-data (fetch-url "http://www.eatingwell.com/recipes/scallop_scampi.html"))

